//节点的类

class Node{
    constructor(element){
        this.element = element; //value
        this.next = null; //指向下一个节点的指针
    }
}

//单向链表类
class LinkList{
    constructor(){
        this.head = null;  //记录首节点
        this.count = 0;    //记录链表当前的个数
    }

    //添加节点
    push(element){
        let node = new Node(element);
        //1.链表为空
        if(this.head === null){
            this.head = node;
        }else{
            //2.链表不为空
            //2.1 找链表里最后一个节点，特征：next 指向是空
            let current = this.head; //首节点存到current变量里
            while(current.next != null){
                current = current.next;
            }
            current.next = node;
        }
        this.count++;
    }

    //找到指定节点
    getNode(index){   //0
        let current = this.head;
        for(let i = 0; i < index;i++){
            current = current.next;
        }
        return current
    }

    //插入节点
    insert(element,index){
        //边界值的判断 
        if(index >= 0 && index <= this.count){
            let node = new Node(element);
            if(index === 0){
                //1.从开头插入
                if(this.head === null){
                    this.head = node;
                }else{
                    let current = this.head;  //记录首节点
                    this.head = node;
                    node.next  = current;
                }
            }else{
                //2.不是从开头插入
                let prev = this.getNode(index-1);
                let current = prev.next;
                prev.next = node;
                node.next = current;
            }
            this.count++;
        }else{
            return false
        }
    }

    //删除
    removeAt(index){
        //边界值的判断
        if(index >= 0 && index < this.count){
            let current = this.head; //记录首节点
            //1.是否在开头删除
            if(index === 0){
                //1.1从开头删除
                
                this.head = current.next;
            }else{
                //1.2不是从开头删除
                let prev = this.getNode(index-1);//上一个节点
                current = prev.next;
                prev.next = current.next;
            }
            this.count--;
            return current.element;
        }else{
            return undefined
        }
    }

    //查找下标
    indexOf(element){
        let current = this.head;
        for(let i = 0;i<this.count;i++){
            if(current.element === element){
               return i;
            }else{
                current = current.next;
            }
        }
        return -1
    }

    size(){
        return this.count
    }

    isEmpty(){
        return this.count === 0
    }

    getHead(){
        return this.head
    }
}

let l = new LinkList();

l.push('1');

l.push('2');

l.push('3');

l.push('4');

// l.insert('c',0);

// l.insert('d',0)
// console.log(l.removeAt(0));

// console.log(l.removeAt(1));

console.log(l.indexOf('0'));

console.log(l)